import PlaceHolderCpn from '@/components/PlaceHolderCpn';
import {
  ModalForm,
  ProFormDatePicker,
  ProFormDigit,
  ProFormText,
  ProFormTextArea,
  ProTable,
  ProColumns,
} from '@ant-design/pro-components';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { message } from 'antd';
import { useState } from 'react';
import { queryPaymentRecords, refund } from '../service';
import {
  PaymentOrderInfoItem,
  PaymentRecordTableItem,
  PaymentRefundStatus,
  PaymentStatus,
  PayMode,
  RefundParam,
} from '../types.d';

const PaymentList = () => {
  const [orderInfos, setOrderInfos] = useState<PaymentOrderInfoItem[]>([]);
  const [ordersVisible, setOrdersVisible] = useState<boolean>(false);
  const [payOrderNo, setPayOrderNo] = useState<string>('');
  const [refundVisible, setRefundVisible] = useState<boolean>(false);
  const [currOrder, setCurrOrder] = useState<PaymentOrderInfoItem>();
  const [refundStatus, setRefundStatus] = useState<PaymentRefundStatus>(PaymentRefundStatus.NORMAL);

  const columns: ProColumns<PaymentRecordTableItem>[] = [
    {
      title: '车牌号码',
      dataIndex: 'plateNumber',
      align: 'center',
      hideInForm: true,
    },
    {
      title: '用户手机号',
      dataIndex: 'phone',
      tooltip: '仅注册用户可查询此项',
      hideInForm: true,
      hideInTable: true,
    },
    {
      title: '平台记录编号',
      align: 'center',
      dataIndex: 'payNo',
      hideInForm: true,
    },
    {
      title: '支付方记录编号',
      align: 'center',
      dataIndex: 'payOrderNo',
      hideInForm: true,
    },
    {
      title: '支付金额',
      dataIndex: 'amount',
      hideInSearch: true,
      hideInForm: true,
      align: 'center',
      valueType: 'money',
      renderText: (text) => (text / 100).toFixed(2),
    },
    {
      title: '支付方式',
      align: 'center',
      dataIndex: 'payMode',
      valueEnum: {
        [PayMode.TENPAY]: { text: '微信支付' },
        [PayMode.ALIPAY]: { text: '支付宝' },
        [PayMode.CASH]: { text: '现金支付' },
        [PayMode.THIRD_PARTY]: { text: '第三方平台' },
        [PayMode.ETC]: { text: 'ETC' },
        [PayMode.UNKNOWN]: { text: '其他' },
      },
    },
    {
      title: '支付状态',
      align: 'center',
      dataIndex: 'paymentStatus',
      hideInTable: true,
      hideInForm: true,
      valueEnum: {
        [PaymentStatus.ONGOING]: { text: '正在支付' },
        [PaymentStatus.SUCCESS]: { text: '成功' },
        [PaymentStatus.NOTPAY]: { text: '未支付' },
        [PaymentStatus.CLOSED]: { text: '已关闭' },
        [PaymentStatus.REVOKED]: { text: '已撤销' },
        [PaymentStatus.USERPAYING]: { text: '用户支付中' },
        [PaymentStatus.PAYERROR]: { text: '支付失败' },
      },
    },
    {
      title: '支付时间',
      align: 'center',
      dataIndex: 'payTime',
      valueType: 'dateTime',
      renderFormItem: () => <ProFormDatePicker />,
    },
    {
      title: '收费员',
      align: 'center',
      dataIndex: 'cashier',
      renderText: (val) => val || '暂无数据',
    },
    {
      title: '退款状态',
      align: 'center',
      dataIndex: 'isRefund',
      valueEnum: {
        0: { text: '未退款' },
        1: { text: '退款中' },
        2: { text: '已退款' },
        3: { text: '部分退款' },
      },
    },
    {
      title: '操作',
      valueType: 'option',
      align: 'center',
      fixed: 'right',
      render: (_, record) =>
        record?.orderInfos?.length > 0
          ? [
              <a
                key={`${record._id}_detail`}
                onClick={() => {
                  setOrderInfos(record.orderInfos);
                  setPayOrderNo(record.payOrderNo);
                  setRefundStatus(record.isRefund);
                  setOrdersVisible(true);
                }}
              >
                明细
              </a>,
            ]
          : [<PlaceHolderCpn text="暂无明细" />],
    },
  ];
  return (
    <PageHeaderWrapper
      header={{
        title: '',
        subTitle: '支付记录',
        breadcrumb: {
          routes: [
            { path: '/', breadcrumbName: '首页' },
            { path: '/parking-orders', breadcrumbName: '订单管理' },
            { path: '/parking-orders/payments', breadcrumbName: '支付记录列表' },
          ],
        },
      }}
    >
      <ProTable<PaymentRecordTableItem>
        columns={columns}
        rowKey="_id"
        scroll={{ x: true }}
        search={{ labelWidth: 'auto' }}
        style={{ whiteSpace: 'nowrap' }}
        columnEmptyText="暂无数据"
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          defaultPageSize: 10,
          size: 'default',
        }}
        debounceTime={300}
        request={async (param, sort) => {
          const res = await queryPaymentRecords(param, sort);
          return res;
        }}
      />
      {ordersVisible && (
        <ModalForm
          title="费用明细"
          submitter={false}
          visible={ordersVisible}
          modalProps={{
            destroyOnClose: true,
            onCancel: () => {
              setOrdersVisible(false);
              setOrderInfos([]);
            },
          }}
        >
          <ProTable<PaymentOrderInfoItem>
            columns={[
              {
                title: '订单编号',
                dataIndex: 'orderNo',
                align: 'center',
              },
              {
                title: '支付金额',
                dataIndex: 'amount',
                valueType: 'money',
                align: 'center',
                renderText: (text) => (text / 100).toFixed(2),
              },
              {
                title: '操作',
                valueType: 'option',
                align: 'center',
                render: (_, record) =>
                  refundStatus != PaymentRefundStatus.REFUNDED
                    ? [
                        <a
                          onClick={() => {
                            setCurrOrder(record);
                            setRefundVisible(true);
                          }}
                        >
                          退款
                        </a>,
                      ]
                    : [<PlaceHolderCpn text="无可退款" />],
              },
            ]}
            pagination={{
              showSizeChanger: true,
              showQuickJumper: true,
              defaultPageSize: 10,
              size: 'small',
            }}
            options={false}
            size="small"
            search={false}
            dataSource={orderInfos}
          />
        </ModalForm>
      )}
      {refundVisible && currOrder && (
        <ModalForm<RefundParam>
          title="退款申请"
          width="35vw"
          layout="horizontal"
          modalProps={{
            destroyOnClose: true,
            onCancel: () => {
              setRefundVisible(false);
              setCurrOrder(undefined);
            },
          }}
          visible={refundVisible}
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 14 }}
          onFinish={async (values) => {
            const res = await refund({
              payOrderNo,
              reason: values.reason,
              refundTo: values.refundTo,
              refundAmount: parseInt((values.refundAmount * 100).toFixed(0)),
              orderNo: currOrder.orderNo,
            });
            if (res.success) {
              message.success({ key: 'refund', content: res.message });
              return true;
            }
            message.error({ key: 'refund', content: res.message });
            return false;
          }}
        >
          <ProFormText
            label="退款订单"
            name="orderNo"
            initialValue={currOrder.orderNo}
            disabled
            required
          />
          <ProFormText
            label="退款记录"
            name="payOrderNo"
            initialValue={payOrderNo}
            disabled
            required
          />
          <ProFormDigit
            label="退款金额"
            required
            name="refundAmount"
            initialValue={currOrder.amount / 100}
            fieldProps={{
              max: currOrder.amount / 100,
              min: 0,
              precision: 2,
            }}
          />
          <ProFormText
            label="退款用户"
            name="refundTo"
            placeholder="请填写退款用户信息(如手机号)"
          />
          <ProFormTextArea label="退款原因" name="reason" placeholder="请填写退款原因" />
        </ModalForm>
      )}
    </PageHeaderWrapper>
  );
};

export default PaymentList;
